<template>
  <div>
    <el-form :inline="true" :model="searchForm" ref="formRef">
      <el-form-item label="球队名称" prop="user">
        <el-input v-model="searchForm.user" placeholder="请输入球队名称" />
      </el-form-item>
      <el-form-item label="审核状态" prop="region">
        <el-select v-model="searchForm.region" placeholder="请选择审核状态">
          <el-option v-for="item in auditStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchTeamList">查询</el-button>
        <el-button @click="onReset(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="state.tableData" border style="width: 100%">
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="teamName" label="球队名称" width="180" />
      <el-table-column prop="status" label="审核状态">
        <template #default="scope">
          <el-tag :type="AuditStatusText[scope.row.auditStatus as keyof typeof AuditStatusText].type">
            {{ AuditStatusText[scope.row.auditStatus as keyof typeof AuditStatusText].text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="coachStaffCount" label="教练组人数" />
      <el-table-column prop="playerCount" label="队员人数" />
      <el-table-column prop="captain" label="负责人" />
      <el-table-column prop="captainPhoneNumber" label="手机号" />
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button @click="handleDrawerShow(scope.row)">查看</el-button>
          <el-button @click="handleAudit(scope.row.teamId)">审核</el-button>
          <ExportButton 
            :path="REGISTER_EXPORT_PATH"
            :fileName="REGISTER_EXPORT_FILE_NAME"
            :params="{raceId: route.query.id, teamId:scope.row.teamId}" 
            buttonType="default" 
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 球队查看 -->
    <TeamReviewDrawer ref="teamReviewDrawerRef" />
    <!-- 球队审核 -->
    <el-dialog v-model="state.dialogVisible" title="球队审核" width="30%">
      <el-input v-model="state.rejectReason" :rows="3" type="textarea" placeholder="请输入原因..." />
      <div class="dialog-btns">
        <el-button type="primary" @click="handleReject">驳回</el-button>
        <el-button type="primary" @click="handleTeamAudit({
          auditStatus: AuditStatus.COMPLETED
        })">通过</el-button>
        <el-button @click="state.dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus'
import { AuditStatusText, RegisterStatusText } from '@/views/competition/config/index'
import { AuditStatus, RegisterStatus } from '@/views/competition/config/enum'
import { getTeamList, teamAudit } from '@/api/match/index'
import TeamReviewDrawer from './components/teamReviewDrawer.vue'
import ExportButton from '@/components/ExportButton/index.vue'
import { REGISTER_EXPORT_PATH , REGISTER_EXPORT_FILE_NAME} from '@/components/ExportButton/config'
import { useRoute } from 'vue-router';
const route = useRoute()

export interface ITableRow {
  teamId: number, //球队ID
  teamName: string, //球队名称
  registerStatus: RegisterStatus, //报名状态
  auditStatus: AuditStatus, //审核状态
  captain: string, //负责人
  captainPhoneNumber: string | null, //负责人联系方式
  coachStaffCount: number, //教练组人数
  playerCount: number //队员人数
}

const formRef = ref<FormInstance>()
const teamReviewDrawerRef = ref<any>()
const searchForm = reactive({
  user: '',
  region: '',
})

const state = reactive<{
  dialogVisible: boolean
  teamId: number | null
  rejectReason: string  // 驳回原因（驳回必填，通过非必填）
  tableData: ITableRow[]
}>({
  dialogVisible: false,
  teamId: null,
  rejectReason: '',
  tableData: []
})

onMounted(() => {
  fetchTeamList()
})

/**
 * 获取球队列表
 */
const fetchTeamList = () => {
  let { id } = route.query;
  getTeamList({
    raceId: id,
    teamName: searchForm.user,
    auditStatus: searchForm.region
  }).then(res => {
    state.tableData = res.data || []
  })
}

// 球队状态下拉框
const auditStatusOptions = computed(() => {
  return Object.keys(AuditStatusText).map(key => {
    return {
      label: AuditStatusText[key as AuditStatus].text,
      value: key
    }
  })
})

const onReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  fetchTeamList()
}

const handleReject = () => {
  if (!state.rejectReason) {
    ElMessage({
      message: '驳回原因不能为空',
      type: 'warning',
    })
  } else {
    handleTeamAudit({
      "auditStatus": AuditStatus.FAILURE, //审核状态
      "reason": state.rejectReason //驳回原因
    })
  }
}

const handleDrawerShow = (row: ITableRow) => {
  teamReviewDrawerRef.value.showDrawer(row)
}

const handleAudit = (teamId: number) => {
  state.dialogVisible = true
  state.teamId = teamId
}

/**
 * 球队审核
 */
const handleTeamAudit = (params: {
  auditStatus: AuditStatus, //审核状态
  reason?: string //驳回原因
}) => {
  let { id } = route.query;
  teamAudit({
    raceId: id, //赛事ID
    teamId: state.teamId, //球队ID
    ...params
  }).then(() => {
    ElMessage.success("审核完成");
    fetchTeamList()
    state.dialogVisible = false
  })
}

</script>

<style lang="scss" scoped>
.el-form .el-form-item:last-of-type {
  margin-bottom: 18px !important;
}

.dialog-btns {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
